package leetcode_2401_2500;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class LeeCode_2491 {
    public static void main(String[] args) {
        System.out.println(dividePlayers(new int[]{3, 2, 5, 1, 3, 4}));
    }
    private static long dividePlayers(int[] skill) {
        int n = skill.length;
        int sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int j : skill) {
            map.put(j, map.getOrDefault(j, 0) + 1);
            sum += j;
        }
        int m = n / 2;
        if (sum % m != 0) {
            return -1;
        }
        int mid = sum / m;
        long ans = 0;
        while (!map.isEmpty()) {
            for (Integer pre : map.keySet()) {
                int next = mid - pre, c1 = map.get(pre);
                if (!map.containsKey(next))
                    return -1;
                if (map.get(next) != c1)
                    return -1;
                if (pre == next){
                    if (c1 % 2 != 0)
                        return -1;
                    ans += (long) pre * next * (c1 / 2);
                    map.remove(pre);
                }else {
                    map.remove(pre);
                    map.remove(next);
                    ans += (long) pre * next * c1;
                }
                break;
            }
        }
        return ans;
    }
}
